class Bill < ActiveRecord::Base

  validates :description, presence: true
  validates :amount,  presence: true, numericality: true

  scope :user_tody_bills, ->(user_id) {where("user_id = ? AND created_at >= ? AND created_at <= ?",
                                             user_id, Time.now.at_beginning_of_day, Time.now.at_end_of_day)}
  scope :user_last_bills, ->() {}

  belongs_to :group
  belongs_to :user
  has_many :containers

  before_save :float_round
  after_save :update_note

  def float_round
    self.amount = self.amount.to_f.round(2)
  end

  def restore_one_bill
    count = self.containers.count.to_f
    money = self.amount/count
    money = money.round(2)
    # Rails.logger.debug "money = #{money} self.amount= #{self.amount}"
    self.containers.each do |item|
      note = Note.user_note(item.user_id).first
      # Rails.logger.debug "note.payment=#{note.payment}"
      if note.user_id == self.user_id
        note.update(payment: note.payment - money, total: note.total - self.amount)
      else
        note.update(payment: note.payment - money)
      end
      Container.delete(item.id)
    end
  end

  def update_one_bill(params = {}, members = [])
    Bill.transaction do
      restore_one_bill
      members.each do |user_id|
        Container.create(bill_id: self.id, user_id: user_id)
      end
      self.update_attributes(params)
    end
  end

  def update_note
    count = self.containers.count.to_f
    money = (self.amount/count).round(2)
    items = self.containers
    items.each do |item|
      note = Note.user_note(item.user_id).first
      if note.user_id == self.user_id
        note.update(payment: note.payment + money, total: note.total+self.amount)
      else
        note.update(payment: note.payment + money)
      end
    end

  end

  def bill_members
    user_ids = []
    self.containers.each do |container|
      user_ids << container.user_id
    end
    # Rails.logger.debug "user_ids = #{user_ids}"
    User.where(id: user_ids)
  end

  def created_time
    if self.created_at.year == Time.now.year
      "#{created_at.month}-#{created_at.day} #{created_at.hour}:#{created_at.min}"
    else
      "#{created_at.year}-#{created_at.month}-#{created_at.day} #{created_at.hour}:#{created_at.min}"
    end
  end

  def bill_owner
    User.find_by_id(self.user_id)
  end

end
